package proxy

import (
	"errors"
	"log"
	"net"
	"strconv"

	"github.com/hashicorp/consul/api"
)

// 声明一个全局变量用于存储Consul客户端
var consulClient *api.Client

// InitConsulClient 初始化Consul客户端
func InitConsulClient(client *api.Client) {
	consulClient = client
}

// ResolveService 从 Consul 获取健康的服务实例
func ResolveService(serviceName string) (string, error) {
	log.Printf("Resolving service: %s", serviceName)

	// 检查Consul客户端是否已初始化
	if consulClient == nil {
		log.Printf("Consul client not initialized")
		return "", errors.New("consul client not initialized")
	}

	// 查询健康的服务实例
	health := consulClient.Health()
	log.Printf("Querying Consul for healthy instances of service: %s", serviceName)
	services, _, err := health.Service(serviceName, "", true, nil)
	if err != nil {
		log.Printf("Error querying Consul for service %s: %v", serviceName, err)
		return "", err
	}

	log.Printf("Found %d healthy instances for service: %s", len(services), serviceName)

	if len(services) == 0 {
		log.Printf("No healthy instances found for service: %s", serviceName)
		return "", ErrNoHealthyInstance
	}

	// 简单轮询或随机选择（这里用第一个）
	node := services[0].Service
	addr := net.JoinHostPort(node.Address, strconv.Itoa(node.Port))
	log.Printf("Selected instance for service %s: %s (Address: %s, Port: %d)", serviceName, node.Service, node.Address, node.Port)
	return addr, nil
}

var ErrNoHealthyInstance = errors.New("no healthy instance available")
